<?php

namespace app\api\model;

use app\exceptions\ApiException;
use think\Exception;
use think\Model;

/**
 * Bill
 */
class Sub extends Model
{
    // 表名
    protected $name = 'member_sub';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    public function subAccount($params)
    {
        $result = self::where(['member_id' => $params['member_id']])->select();
        foreach ($result as &$value) {
            $value['name'] = $value['username'];
            unset($value['username']);
        }
        return api_message($result);
    }


    public function submitAccount($params)
    {
        $id = $params['id'] ?? '';

        // 检查必填字段
        if (empty($params['name']) && empty($params['sex'])) {
            throw new ApiException('请填写完整的信息');
        }

        // 检查亲情账号数量
        $accountNums = self::where(['member_id' => $params['member_id']])->count();
        if ($accountNums >= 5) {
            throw new ApiException('最多添加5个亲情账号');
        }

        // 查找现有账号
        $existingAccount = self::where(['id' => $id])->find();

        // 更新或创建账号
        if ($existingAccount) {
            $existingAccount->username = $params['name'];
            $existingAccount->sex = $params['sex'];
        } else {
            $existingAccount = new self();
            $existingAccount->username = $params['name'];
            $existingAccount->sex = $params['sex'];
            $existingAccount->member_id = $params['member_id']; // 确保添加 member_id
        }
        $existingAccount->save();

        return api_message();
    }



    public function delAccount($params){
         $id = $params['id'] ?? 0;
         $account = self::where(['id' => $id])->find();
         if(!$account){
             throw new ApiException('数据不存在，请刷新后重试');
         }
         self::where(['id' =>$id])->delete();
         return api_message();
    }



}